package com.ruoyi.HKISAPI.controller;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.*;
//
@Component
public class ImageDownloader {

    public static void main(String[] args) {
        String imageUrl = "http://192.168.7.50:80/picture/Streaming/tracks/803/?name=ch00008_01010000030000000000bb4adc10006192f00061a471001&size=399663"; // 图片的URL
        String username = "admin";
        String password = "sxygsj123";
        String localFilePath_Mac = "/Users/wangxiaoxing/Desktop/sql/2024_7/5/15_17_45_705_fielddetection.jpg"; // 本地文件路径
        String localFilePath_Windows = "C:\\Users\\wangxiaoxing\\Desktop\\sql\\2024_7\\5\\15_17_45_705_fielddetection.jpg"; // 本地文件路径（Windows格式）

        try {
            downloadImageWithDigestAuth(imageUrl, username, password, localFilePath_Windows);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void downloadImageWithDigestAuth(String imageUrl, String username, String password, String localFilePath) throws IOException {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "digest"),
                new UsernamePasswordCredentials(username, password));

        // 创建目录
        File dir = new File(localFilePath).getParentFile();
        if (!dir.exists() && !dir.mkdirs()) {
            throw new IOException("无法创建目录: " + dir.getAbsolutePath());
        }

        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build()) {

            HttpGet httpGet = new HttpGet(imageUrl);
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                try (InputStream inputStream = entity.getContent();
                     FileOutputStream outputStream = new FileOutputStream(localFilePath)) {

                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }

                    System.out.println("图片已成功下载到: " + localFilePath);
                }
            } else {
                System.out.println("下载失败，服务器未返回有效内容。");
            }

            EntityUtils.consume(entity); // 确保释放连接
        }
    }
}
